package com.mender.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mender.common.constant.MessageConstant;
import com.mender.common.exception.LoginFailedException;
import com.mender.common.properties.WeChatProperties;
import com.mender.common.utils.HttpClientUtil;
import com.mender.user.domain.dto.UserLoginDTO;
import com.mender.domain.po.User;
import com.mender.user.mapper.UserMapper;
import com.mender.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

//    微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
//        获取用户openid
        String code = userLoginDTO.getCode();
        String openid = getOpenid(code);

//        判断是否为空
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
//        当前用户是否为新用户
        User user = userMapper.getByOpenId(openid);
//        若是新用户 需完成注册
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
//        返回用户对象
        return user;
    }

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }

    /**
     * 新增用户数
     */
    @Override
    public Integer countNewUserByMap(Map<String, Object> params) {
        return userMapper.countByMap(params);
    }

    private String getOpenid(String code){
        //调用微信接口服务 获取用户openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        //        解析json
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
